package com.syaccp.service.impl;

import java.util.concurrent.TimeUnit;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.syaccp.exception.CrmebException;
import com.syaccp.service.ValidateCodeService;
import com.syaccp.utils.ImageUtils;
import com.syaccp.utils.RedisCache;
import com.syaccp.utils.ValidateCodeUtil;
import com.syaccp.vo.ValidateCode;

import cn.hutool.core.util.ObjectUtil;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

	@Autowired
	private RedisCache redisCache;

	@Override
	public ValidateCode get() {

		ValidateCodeUtil.Validate randomCode = ValidateCodeUtil.getRandomCode();// 直接调用静态方法，返回验证码对象
		if (ObjectUtil.isNull(randomCode)) {
			return null;
		}

		String value = randomCode.getValue().toLowerCase();
		String md5Key = DigestUtils.md5Hex(value);
		String redisKey = getRedisKey(md5Key);

		redisCache.setCacheObject(redisKey, value, 5, TimeUnit.MINUTES); // 5分钟过期
		String base64Str = randomCode.getBase64Str();
		return new ValidateCode(md5Key, ImageUtils.getBase64Image(base64Str));
	}

	/**
	 * 获取redis key
	 * 
	 * @param md5Key value的md5加密值
	 */
	public String getRedisKey(String md5Key) {
		return com.syaccp.constants.Constants.VALIDATE_REDIS_KEY_PREFIX + md5Key;
	}

	@Override
	public Boolean check(String key, String code) {

		if (!redisCache.exists(getRedisKey(key))) {
            throw new CrmebException("验证码错误");
        }
        Object redisValue = redisCache.getCacheObject(getRedisKey(key));
        if (ObjectUtil.isNull(redisValue)) {
            return false;
        }
        return redisValue.equals(code.toLowerCase());
	}

}
